package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FocusUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.enums.LikeType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private FocusUserApi focusUserApi;

    /**
     * 上传视频
     *
     * @param videoThumbnail 封面图片文件
     * @param videoFile      视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0301", "video", videoId);
    }

    //查询视频列表
    @Cacheable(
            value = "videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    //userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                String key = Constants.MOVEMENTS_INTERACT_KEY + video.getId();
                // 设置是否已经点赞
                String likeHashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, likeHashKey)) {
                    vo.setHasLiked(1);
                }
                // 设置是否已经关注
                String focusHashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, focusHashKey)) {
                    vo.setHasFocus(1);
                }
                vos.add(vo);
            }
        }

        return new PageResult(page, pagesize, 0L, vos);
    }

    // 视频点赞
    public void likeVideo(String videoId) {
        // 查询是否已经点赞
        Long userId = UserHolder.getUserId();
        if (commentApi.hasComment(videoId, userId, CommentType.LIKE)) {
            // 已点赞，抛出异常
            throw new BusinessException(ErrorResult.error());
        }
        // 保存点赞数据到mongodb并修改视频点赞数
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        videoApi.videoPositiveComment(comment, LikeType.LIKE);
        // 用户的点赞数据写入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().put(key, hashKey, "1");
        // 发送日志消息到mq
        mqMessageService.sendLogMessage(userId, "0302", "video", videoId);
    }

    // 视频点赞-取消
    public void dislikeVideo(String videoId) {
        // 查询是否已经点赞
        Long userId = UserHolder.getUserId();
        if (!commentApi.hasComment(videoId, userId, CommentType.LIKE)) {
            // 未点赞，抛出异常
            throw new BusinessException(ErrorResult.error());
        }
        // 删除点赞数据到mongodb并修改视频点赞数
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.LIKE.getType());
        videoApi.videoNegativeComment(comment, LikeType.DISLIKE);
        // 从rides中删除点赞数据
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key, hashKey);
        // 发送日志到mq
        mqMessageService.sendLogMessage(userId, "0303", "video", videoId);
    }

    // 评论列表
    public PageResult getCommentsOfVideoByPage(String videoId, Integer page, Integer pagesize) {
        // 从mongo获取评论列表
        List<Comment> comments = commentApi.findComments(videoId, CommentType.COMMENT, page, pagesize);
        if (CollectionUtils.isEmpty(comments)) {
            return new PageResult();
        }
        // 根据评论人id列表查询用户详情
        List<Long> ids = comments.stream().map(Comment::getUserId).collect(Collectors.toList());
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        // 封装vo列表
        List<CommentVo> vos = comments.stream()
                .filter(comment -> map.get(comment.getUserId()) != null)
                .map(comment -> CommentVo.init(map.get(comment.getUserId()), comment))
                .collect(Collectors.toList());
        // 封装分页结果
        return new PageResult(page, pagesize, 0L, vos);
    }

    // 评论发布
    public void publishComment(String videoId, String text) {
        Long userId = UserHolder.getUserId();
        // 封装comment对象，保存到mongodb并修改评论数
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setCreated(System.currentTimeMillis());
        comment.setContent(text);
        videoApi.videoPositiveComment(comment, LikeType.LIKE);
        // 发送日志到mq
        mqMessageService.sendLogMessage(userId, "0304", "video", videoId);
    }

    // 视频用户关注
    public void userFocus(Long uid) {
        // 获取当前用户id
        Long userId = UserHolder.getUserId();
        // 查询数据
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(uid);
        focusUser.setFollowUserId(userId);
        // 已关注则结束方法
        if (focusUserApi.exist(focusUser)) {
            return;
        }
        // 未关注，添加数据到关注表
        focusUser.setCreated(System.currentTimeMillis());
        String id = focusUserApi.save(focusUser);
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    // 视频用户关注-取消
    public void userUnFocus(Long uid) {
        // 获取当前用户id
        Long userId = UserHolder.getUserId();
        // 查询数据
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(uid);
        focusUser.setFollowUserId(userId);
        // 未关注则结束方法
        if (!focusUserApi.exist(focusUser)) {
            return;
        }
        // 已关注，从关注表删除数据
        focusUserApi.remove(focusUser);
    }
}
